// promise 队列  阻塞  ,按照task 先后执行， 其中失败将不会往后执行  会在catch 中捕获错误
export class TaskQueueBlocking {
  constructor() {
    this.tasks = [];
  }
  addTask(task) {
    this.tasks.push(task);
  }
  run() {
    const results = [];
    const executeTask = () => {
      if (this.tasks.length === 0) {
        return Promise.resolve(results);
      }
      const task = this.tasks.shift();
      return Promise.resolve(task())
        .then((result) => {
          results.push(result);
          return executeTask();
        })
        .catch((error) => {
          throw new Error(`Task failed: ${error}.`);
        });
    };
    return executeTask();
  }
}
